package com.xm.servlet;


import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.rmi.ServerException;

@WebServlet("/getCode.do")
public class GetCodeServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //生成一个四位数的随机验证码
        String str = "";
        for (int i=0;i<4;i++){
            //Math.floor();向下取整
            str+=(int)Math.floor(Math.random()*10);
        }
        System.out.println(str);
        request.getSession().setAttribute("_code",str);
        //获取前台传送过来的手机号码
        String phone = request.getParameter("phone");
        //判断是否存在该手机号
        sendMsg(phone,str);

    }
    //发送短信验证码方法
    private void sendMsg(String phone,String str){
        DefaultProfile profile = DefaultProfile.getProfile("cn-hangzhou", "LTAI4G5VZdTwgbHd9tNae32D", "aA1oYTv0dgrk8iubZx4Ztmco9j63Zw");
        /*IAcsClient client = new DefaultAcsClient(profile);*/
        IAcsClient client = new DefaultAcsClient(profile);
        CommonRequest request = new CommonRequest();
        request.setMethod(MethodType.POST);
        request.setDomain("dysmsapi.aliyuncs.com");
        request.setVersion("2017-05-25");
        request.setAction("SendSms");
        request.putQueryParameter("RegionId", "cn-hangzhou");
        request.putQueryParameter("PhoneNumbers", phone);
        request.putQueryParameter("SignName", "汪汪特工");
        request.putQueryParameter("TemplateCode", "SMS_198932141");
        request.putQueryParameter("TemplateParam", "{'code':'"+str+"'}");
        try {
            CommonResponse response = client.getCommonResponse(request);
            System.out.println(response.getData());
        } catch (ClientException e) {
            e.printStackTrace();
        }
    }
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request,response);
    }
}
